import Taro, { Component } from '@tarojs/taro'
import { View, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import Enum from '../../constants/Enum'

import './index.less'

import Title from '../../component/Title'
import Banner from '../../component/Banner'
import Choice from '../../component/Choice'
import { login } from '../../store/actions/login'
import { getAllHistory } from '../../store/actions/practice'

@connect((state) => ({
  login: state.system.login
}))
class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLogin: false
    }
  }
  config = {
    navigationBarTitleText: '百格计算',
    navigationBarBackgroundColor: '#6C8AF8',
    navigationBarTextStyle: 'white'
  }
  componentDidShow() {
    this.getAllHistory()
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.login !== this.props.login) {
      this.getAllHistory()
    }
  }
  getUserinfo = (e) => {
    let self = this
    const { dispatch } = this.props
    Taro.login()
      .then(res => {
        Taro.setStorageSync(Enum.userInfo, JSON.stringify(e.detail.userInfo))
        self.setState({
          isLogin: true
        })
        const { userInfo } = e.detail
        dispatch(login({
          code: res.code,
          photo: userInfo.avatarUrl,
          nickname: userInfo.nickName
        }))
      })
  }
  getSessionKey = () => {
    return Taro.getStorageSync(Enum.session_key)
  }
  getAllHistory = () => {
    let session_key = this.getSessionKey()
    if (session_key) {
      this.props.dispatch(getAllHistory())
    }
  }
  render () {
    let session_key = this.getSessionKey()
    const { isLogin } = this.state
    return (
      <View className='index'>
        {
          (session_key === '' && isLogin === false) ? (
            <Button
              className='loginBtn'
              plain
              openType='getUserInfo'
              onGetUserInfo={this.getUserinfo}
            >
            </Button>
          ) : null
        }
        <Title />
        <Banner />
        <Choice />
      </View>
    )
  }
}

export default Index
